package com.bite.common.security.service;


import cn.hutool.core.lang.UUID;
import com.bite.common.core.constants.CacheConstants;
import com.bite.common.core.constants.JwtConstants;
import com.bite.common.core.domain.LoginUser;
import com.bite.common.redis.service.RedisService;
import com.bite.common.core.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class TokenService {
    @Value("${jwt.secret}")
    private String secret;
    @Autowired
    private RedisService redisService;
    public String createToken(Long userId, String secret,Integer identity,String nickName,String headImage ) {
        //生成token
        //claims 存储着用户唯一标识信息uuid
        Map<String, Object> claims = new HashMap<>();
        String userKey = UUID.fastUUID().toString();
        //用于唯一标识
        claims.put(JwtConstants.LOGIN_USER_ID, userId);
        claims.put(JwtConstants.LOGIN_USER_KEY, userKey);
        //返回给客户端
        String token = JwtUtils.createToken(claims, secret);

        //第三方工具（redis）中存入敏感信息
        //存啥   用户身份 identity   1 普通用户  2 管理员用户
        //使用什么数据结构  String    key    value 用户身份
        //key: 保持唯一 便于维护 统一前缀  loginToken+userId（雪花算法）

        String tokenKey = CacheConstants.LOGIN_TOKEN_KEY + userKey;
        LoginUser loginUser = new LoginUser();
        loginUser.setIdentity(identity);
        loginUser.setNickName(nickName);

        loginUser.setHeadImage(headImage);
        //将 存入redis
        redisService.setCacheObject(tokenKey,loginUser,CacheConstants.EXP, TimeUnit.MINUTES);
        return token;
    }


    //延迟token的有效时间 就是延长redis中存储用户身份认证的敏感信息的有效时间
    //啥时候执行验证token有效时间？  答案：在拦截器中执行

    //身份认证之后执行 AuthFilter
    //并且到达controller之前执行
    public void extendToken(Claims claims) {
        String userKey = getUserKey(claims);
        String tokenKey = CacheConstants.LOGIN_TOKEN_KEY + userKey;

        //720m  12h  剩余3h 进行延长

        //获取剩余时间
        Long expire = redisService.getExpire(tokenKey, TimeUnit.MINUTES);
        if(expire != null && expire < CacheConstants.REFRESH_TIME) {
            redisService.expire(tokenKey,CacheConstants.EXP, TimeUnit.MINUTES);
        }

    }

    public LoginUser getLoginUser(String token,String secret) {
        //从jwt中获取载荷  再从载荷中获取唯一标识
        String userKey = getUserKey(token, secret);
        if(userKey == null) {
            return null;
        }
       return redisService.getCacheObject(getTokenKey(userKey), LoginUser.class);

    }
    private String getTokenKey(String userKey) {
        return CacheConstants.LOGIN_TOKEN_KEY + userKey;
    }
    private String getUserKey(String token, String secret) {
        Claims claims = getClaims(token, secret);
        if (claims == null) return null;
        String userKey = JwtUtils.getUserKey(claims);  //获取jwt中的key
        return userKey;
    }

    public Claims getClaims(String token, String secret) {
        Claims claims;
        try {
            claims = JwtUtils.parseToken(token, secret); //获取令牌中信息  解析payload中信息  存储着用户唯一标识信息uuid
            if (claims == null) {
                log.error("解析token:{},出现异常", token);
                return null;
            }
        } catch (Exception e) {
            log.error("解析token:{},出现异常", token,e);
            return null;
        }
        return claims;
    }

    public Long getUserId(String token, String secret) {
        Claims claims = getClaims(token, secret);
        if (claims == null) return null;
        String userId = JwtUtils.getUserId(claims);  //获取jwt中的key
        return Long.valueOf(userId);
    }
    public Long getUserId(Claims claims) {
        if (claims == null) return null;
        return Long.valueOf(JwtUtils.getUserId(claims));  //获取jwt中的key
    }

    public String getUserKey(Claims claims) {
        if (claims == null) return null;
        return JwtUtils.getUserKey(claims);  //获取jwt中的key
    }

    public boolean logout(String token, String secret) {
        String userKey = getUserKey(token, secret);
        if(userKey == null) {
            return false;
        }
        return redisService.deleteObject(getTokenKey(userKey));

    }

    public void refreshLoginUser(String nickName, String headImage, String userKey) {
        LoginUser loginUser = redisService.getCacheObject(getTokenKey(userKey), LoginUser.class);
        loginUser.setNickName(nickName);
        loginUser.setHeadImage(headImage);
        redisService.setCacheObject(getTokenKey(userKey),loginUser);
    }
}
